package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //根据分类id和status=1查询菜品信息
    @GetMapping("/dish/list")
    public ResultInfo findList(Long categoryId, @RequestParam(defaultValue = "1") Integer status,String name) {
       String key= "dish_"+categoryId;
       //先从redis中查询
        List<Dish> dishList = (List<Dish>)redisTemplate.opsForValue().get(key);
        //如果redis中存在，在直接返回
        if (CollectionUtils.isNotEmpty(dishList)){
            return ResultInfo.success(dishList);
        }else {
            //如果内存中没有则从数据库中查询，另外把它存到内存中方便下一次查询
            dishList = dishService.findList(categoryId, status,name);
            //然后把它存到redis中
            redisTemplate.opsForValue().set(key,dishList);
            return ResultInfo.success(dishList);
        }



    }
}